
import { type PaginationProps } from "@pureadmin/table";
import {
  PersonalCreditScoreMeasurementGetAllByPagedAndSort,
  EnterpriseCreditResultDGaeeilstt,
  PersonalCreditScoreMeasurementCreate
} from "@/api/stu/DataScene";
import { ElMessage, FormInstance } from "element-plus";
import { useRoute } from "vue-router";
import { ref, reactive, nextTick, watch, onMounted } from "vue";
import qs from "qs";
export function useCreditReport() {
  const route = useRoute()
  const dataList = ref<any>([]);
  const ShowReport = ref<string>();
  const ScoreParticulars_ = ref();
  const loading = ref<boolean>(true);
  const btnloading = ref<boolean>(false);
  const CreditVisible = ref<boolean>(false);
  const CreditReportVisible = ref<boolean>(false);
  const regex = /^[\u4e00-\u9fa5]{2,4}$/;// 校验2-4个字中文
  const regPhone = /^1[3456789]\d{9}$/;
  const regID = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "姓名",
      prop: "personName",
    },
    {
      label: "身份证号码",
      prop: "idCard",
    },
    {
      label: "测算模型",
      prop: "modelName",
    },
    {
      label: "信用分",
      prop: "creditScore",
    },
    {
      label: "信用等级",
      prop: "creditRating",
      cellRenderer: ({ row }) => (
        <span>
          {
            row.creditRating === "1" ? "较差" :
              row.creditRating === "2" ? "中等" :
                row.creditRating === "3" ? "良好" :
                  row.creditRating === "4" ? "优秀" :
                    row.creditRating === "5" ? "极好" : ""
          }
        </span>
      )
    },
    // {
    //   label: "查询时间",
    //   prop: "createTime",
    // },
    {
      label: "操作",
      fixed: "right",
      width: 160,
      slot: "operation"
    }
  ];

  const CreditScoreFrom = reactive({
    name: "",
    id: ""
  })

  const rule = {
    name: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (regex.test(CreditScoreFrom.name) === false) {
            return callback(new Error('请输2-4的中文名称'))
          } else {
            // 校验通过
            return callback()
          }
        },
        trigger: ["blur", "change"],
      }
    ],
    id: [
      {
        required: true,
        trigger: ["blur", "change"],
        validator: (rule: any, value: any, callback: () => void) => {
          if (regID.test(CreditScoreFrom.id) === false) {
            return callback(new Error('请输入正确的身份证号码'))
          } else {
            // 校验通过
            return callback()
          }
        },
      }
    ],
  }

  // 申请测算信用评分
  function ApplyCreditScore() {
    CreditVisible.value = true;
  }
  // 取消关闭
  function CloseVisible(row: FormInstance | undefined) {
    CreditVisible.value = false;
    row.resetFields();
  };

  // 确定
  async function SubmitVisible(row: FormInstance | undefined) {
    (row as any).validate(async valid => {
      if (!valid) return;
      const data = {
        personName: CreditScoreFrom.name,
        idCard: CreditScoreFrom.id,
        "planId": route.query.planId,
        "taskId": route.query.taskId
      }
      btnloading.value = true;
      const res = await PersonalCreditScoreMeasurementCreate(data);
      if (res.success) {
        ElMessage.success(res.msg)
        row.resetFields();
        GetMarketOriented()
        btnloading.value = false;
        CreditVisible.value = false;
      } else {
        ElMessage.error(res.msg);
        setTimeout(() => { btnloading.value = false; }, 1500)
      }
    })
  }

  // 获取市场征信
  async function GetMarketOriented() {
    const res = await PersonalCreditScoreMeasurementGetAllByPagedAndSort({
      planId: route.query.planId,
      taskId: route.query.taskId,
      "pageIndex": pagination.currentPage,
      "pageCount": pagination.pageSize
    });
    if (res.success) {
      pagination.total = res.data.totalCount;
      dataList.value = res.data.items;
      loading.value = false
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading.value = false }, 1500)
    }
    // pagination.total = respone.data.totalCount;
    // dataList.value = respone.data.items;
  }

  // 查看个人征信报告详情
  async function CheckCreditReport(row) {
    const data = qs.stringify({
      modelId: row.personalCreditModelId,
      enterpriseId: row.pcsmId
    })
    const res = await EnterpriseCreditResultDGaeeilstt(data);
    if (res.success) {
      const data = {
        data: res.data,
        grade: row.creditRating === "1" ? "较差" :
          row.creditRating === "2" ? "中等" :
            row.creditRating === "3" ? "良好" :
              row.creditRating === "4" ? "优秀" :
                row.creditRating === "5" ? "极好" : "无",
        score: row.creditScore
      }
      ScoreParticulars_.value.ViewScore(data);
    } else {
      ElMessage.error(res.msg);
    }
    // const res = await EnterpriseCreditResultDGaeeilstt(data);
    // if (res.success) {
    //   console.log("success", res)
    //   ScoreParticulars_.value.ViewScore(res.data)
    //   // nextTick(() => {
    //   //   ShowReport.value = res.data
    //   // })
    // } else {
    //   ElMessage.error(res.msg)
    // }
  }

  onMounted(() => {
    GetMarketOriented()
  })

  return {
    rule,
    dataList,
    loading,
    CreditVisible,
    pagination,
    columns,
    btnloading,
    ShowReport,
    CreditScoreFrom,
    ScoreParticulars_,
    CreditReportVisible,
    CheckCreditReport,
    ApplyCreditScore,
    SubmitVisible,
    CloseVisible
  }
}
